package com.itheima.manager.dao;

import com.itheima.manager.domain.Subway;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class SubwayDao {
    static ArrayList<Subway> list = new ArrayList<Subway>();

    static {
        load01();
    }

    private static void load01() {
        try {
            BufferedReader br = new BufferedReader(new FileReader("地铁系统案例二\\subways.txt"));
            String line;
            while ((line = br.readLine()) != null) {
                String[] split = line.split(",");
                list.add(new Subway(split[0], split[1], split[2]));
            }
            br.close();
        } catch (IOException e) {
            System.out.println("加载文件出现异常................");
        }

    }


    private static void reSave01() {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("地铁系统案例二\\subways.txt"));
            for (Subway subway : list) {
                bw.write(subway.toString());
                bw.newLine();
            }
            bw.close();
        } catch (IOException e) {
            System.out.println("保存集合数据到文件出现异常............");
        }

    }

    public ArrayList<Subway> selectSubways() {
        return list;
    }

    public void addSubway(Subway sub) {
        list.add(sub);
        reSave01();
    }

    public void deleteSubway(String id) {
        int index = byIdGetIndex(id);
        list.remove(index);
        reSave01();
    }

    private int byIdGetIndex(String id) {
        int index = -1;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) != null && id.equals(list.get(i).getId())) {
                index = i;
                break;
            }
        }
        return index;
    }

    public Subway updateSubway(String id, Subway sub) {
        int index = byIdGetIndex(id);
        reSave01();
        return list.set(index, sub);
    }
}
